from flask import  Flask, render_template,request,escape
import requests
import json
import http.client, urllib.request, urllib.parse, urllib.error, base64


app = Flask(__name__)
def log_request(req:"flask request",res:str):
	with open("vsearch.log","a") as log:
		print(req.form,req.host_url,req.remote_addr,file=log,sep="|")

@app.route("/login",methods=['get'])
def index()-> 'html':
    title ='welcome'
    return render_template("login.html",the_title=title)


@app.route('/entry',methods=['post','get'])
def hello_entry():
    user = request.form.get("user")
    log_request(request,user)
    return render_template('entry.html',the_title='图片识别网')

@app.route('/face',methods=['post'])
def face(): 
	img_url=request.form["face"]
	KEY = 'bdd5fd9b6bfa4fae97e37efa2ddc5fe7'                                   
	BASE_URL =  'https://hzxnewmedia-face-identify.cognitiveservices.azure.com//face/v1.0/detect'           
	HEADERS = {
	    'Content-Type': 'application/json',                          
	    'Ocp-Apim-Subscription-Key': '{}'.format(KEY),  
	}
	data = {
	    'url': '{}'.format(img_url),
	}
	payload = {
	    'returnFaceId': 'true',
	    'returnFaceLandmarks': 'flase',                      
	    'returnFaceAttributes': '{}'.format('age,gender,glasses'), 
	}
	r = requests.post(BASE_URL,data=json.dumps(data),params = payload,headers=HEADERS)                                                    
	result=r.json()
	a=result[0][ 'faceAttributes']                              
	return render_template('entry.html',r=str(a),img_url4=img_url)
	

@app.route("/viewlog")
def view_log():
 contents=[]
 with open("vsearch.log","r") as log:
  for line in log:
   contents.append([])
   for item in line.split("|"):
    contents[-1].append(escape(item))
  titles= ["Formdata","Host_url","Remote_addr"]
 return render_template('view.html',the_data=contents,the_titles=titles)


if __name__ == '__main__':
	app.run(debug= True)